package com.woshua.handler;

import com.woshua.annotation.ViewInjector;
import com.woshua.utils.AnnotationUtil;
import com.woshua.utils.FileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;

/*
* 处理带有ViewInject注解的属性
* */
public class ViewInjectHandler implements AnnotationHandler {

    private ProcessingEnvironment processingEnvironment;

    @Override
    public void attachProcessingEnvironment(ProcessingEnvironment env) {
        processingEnvironment =env;
    }

    @Override
    public Map<String, List<VariableElement>> handAnnotation(RoundEnvironment environment) {
//        获取一个类上带有ViewInject注解的属性列表,并把这些属性列表放入map中返回
        Map<String, List<VariableElement>> map=new HashMap<>();

        Set<? extends Element> elementSet = environment.getElementsAnnotatedWith(ViewInjector.class);

//        那个属性属于哪一个类
        for (Element element : elementSet) {
            VariableElement variableElement= (VariableElement) element;

//            获取类名
            String className=getParentClassName(variableElement);
            List<VariableElement> variableElements = map.get(className);
            if(variableElements==null)
            {
                variableElements=new ArrayList<>();
                map.put(className,variableElements);
            }
            FileUtils.print(className+"--"+variableElement.getSimpleName().toString()+"\r\n");
            variableElements.add(variableElement);
        }
        return map;
    }

    /*
    * 获取所属属性的类名
    * */
    private String getParentClassName(VariableElement variableElement) {
        TypeElement typeElement = (TypeElement) variableElement.getEnclosingElement();
        String packageName= AnnotationUtil.getPackageName(processingEnvironment,typeElement);
        return packageName+"."+typeElement.getSimpleName().toString();
    }
}
